package com.xiaoyu.lanling.feature.guard.fragment

import `in`.srain.cube.util.StringUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.xiaoyu.base.model.User
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.BaseFragment
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.gift.GiftSelectEvent
import com.xiaoyu.lanling.event.guard.CloseEvent
import com.xiaoyu.lanling.feature.gift.ChatGiftBottomSheetDialog
import com.xiaoyu.lanling.router.Router
import kotlinx.android.synthetic.main.guard_detail_me_guarded_fragment.*

class GuardDetailMeGuardedFragment : BaseFragment() {

    companion object {
        fun newInstance(guardee: User, guarder: User, from: String): GuardDetailMeGuardedFragment {
            val arguments = Bundle()
            arguments.putSerializable(Constant.IntentKey.KEY_GUAREE, guardee)
            arguments.putSerializable(Constant.IntentKey.KEY_GUARER, guarder)
            arguments.putString(Constant.PARAM_FROM, from)

            val fragment = GuardDetailMeGuardedFragment()
            fragment.arguments = arguments
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.guard_detail_me_guarded_fragment, container, false)
    }

    override fun onViewCreatedSafelyAfterAppFinishInit(view: View, savedInstanceState: Bundle?) {
        super.onViewCreatedSafelyAfterAppFinishInit(view, savedInstanceState)

        initView()
        initBind()
    }

    private fun initView() {
        val from = arguments?.getString(Constant.PARAM_FROM) ?: ""
        profile_button.text = when (from) {
            Constant.From.GUARD_LIST -> getString(R.string.guard_detail_me_guarded_upgrade_button)
            Constant.From.USER -> getString(R.string.guard_detail_me_guarded_profile_button)
            else -> StringUtil.blank()
        }
        profile_button.setViewTag(from)
    }

    private fun initBind() {
        profile_button.setOnClickDebounceListener { view ->
            val from = view.getViewTag<String>()
            val guarder = (arguments?.getSerializable(Constant.IntentKey.KEY_GUARER) as? User)
                    ?: return@setOnClickDebounceListener
            val activity = activity ?: return@setOnClickDebounceListener

            when (from) {
                Constant.From.GUARD_LIST -> ChatGiftBottomSheetDialog.show(childFragmentManager, guarder, from)
                Constant.From.USER -> Router.instance.gotoUserActivity(activity, guarder)
            }
        }
        know_button.setOnClickDebounceListener {
            CloseEvent().post()
        }
    }
}